package com.ahrhyj.web.controller.system;

import com.ahrhyj.common.core.controller.BaseController;
import com.ahrhyj.common.core.domain.AjaxResult;
import com.ahrhyj.common.core.page.TableDataInfo;
import com.ahrhyj.system.domain.SmsLog;
import com.ahrhyj.system.service.ISmsLogService;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * smsController
 * 
 * @author sentiment
 * @date 2020-09-11
 */
@Api(tags = "短信验证码")
@RestController
@RequestMapping("/sms")
public class SmsLogController extends BaseController
{
    @Autowired
    private ISmsLogService smsLogService;

    /**
     * 查询sms列表
     */
    @PreAuthorize("@ss.hasPermi('system:sms:list')")
    @GetMapping("/list")
    public TableDataInfo list(SmsLog smsLog)
    {
        startPage();
        PageHelper.orderBy("stime desc");
        List<SmsLog> list = smsLogService.selectSmsLogList(smsLog);
        return getDataTable(list);
    }


    /**
     * 获取sms详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sms:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(smsLogService.selectSmsLogById(id));
    }


    /**
     * 验证码发送
     * @param phonenumber
     * @return
     */
    @ApiOperation("短信验证码发送")
    @PostMapping("/code")
    public AjaxResult getSmsCode(@RequestParam("phonenumber") String phonenumber) {
        if (smsLogService.querySendCountToday(phonenumber) > 10){
            return AjaxResult.error("您的手机发送验证码已达上限，请次日再试!");
        }
        String message = "您的短信验证码是%s,十分钟有效,如非本人操作，请忽略本短信";
        return smsLogService.sendSms(phonenumber, message, 1);
    }

    @PostMapping("/valid")
    public AjaxResult valid(@RequestParam("phonenumber") String phonenumber,@RequestParam("code") String code) {
        int result = smsLogService.validSms(phonenumber, code);
        if(result == 0){
            return AjaxResult.success();
        }else if(result == -1){
            return AjaxResult.error("亲，验证码不正确，请重新输入");
        }else if(result == -2){
            return AjaxResult.error("请先获取验证码");
        }else if(result == -3){
            return AjaxResult.error("验证码已过期,请重新获取");
        }else{
            return AjaxResult.error("亲，验证码不正确，请重新输入");
        }
    }
}
